package org.ljy.lotterysystem.service.impl;

import org.ljy.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import org.ljy.lotterysystem.common.exception.ServiceException;
import org.ljy.lotterysystem.controller.param.CreatePrizeParam;
import org.ljy.lotterysystem.controller.param.PageParam;
import org.ljy.lotterysystem.dao.dataobject.PrizeDO;
import org.ljy.lotterysystem.dao.mapper.PrizeMapper;
import org.ljy.lotterysystem.service.IPictureService;
import org.ljy.lotterysystem.service.IPrizeService;
import org.ljy.lotterysystem.service.dto.PageListDTO;
import org.ljy.lotterysystem.service.dto.PrizeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Service
public class PrizeServiceImpl implements IPrizeService {

    @Autowired
    private IPictureService pictureService;

    @Autowired
    private PrizeMapper prizeMapper;

    @Override
    public Long createPrize(CreatePrizeParam param, MultipartFile picFile) {
        //1.上传图片
        String fileName = pictureService.savePicture(picFile);
        //2.构造dao层数据
        PrizeDO prize = new PrizeDO();
        prize.setPrice(param.getPrice());
        prize.setName(param.getPrizeName());
        prize.setDescription(param.getDescription());
        prize.setImageUrl(fileName);
        //3.调用dao
        prizeMapper.insert(prize);
        System.out.println("===="+prize.getId());
        return prize.getId();
    }

    @Override
    public PageListDTO<PrizeDTO> findPrizeList(PageParam param) {
        //1.校验参数
        if(null == param) {
            throw new ServiceException(ServiceErrorCodeConstants.PARAM_ERROR);
        }
        //2.获取总数
        Integer count = prizeMapper.count();
        //3.调用dao
        List<PrizeDO> listDO = prizeMapper.selectPrizeList(param.getCurrentPage(),param.getPageSize());
        //4.封装返回数据列表
        List<PrizeDTO> listDTO = new ArrayList<PrizeDTO>();
        for(PrizeDO prizeDO:listDO) {
            PrizeDTO prizeDTO = new PrizeDTO();
            prizeDTO.setId(prizeDO.getId());
            prizeDTO.setName(prizeDO.getName());
            prizeDTO.setPrice(prizeDO.getPrice());
            prizeDTO.setDescription(prizeDO.getDescription());
            prizeDTO.setImageUrl(prizeDO.getImageUrl());
            listDTO.add(prizeDTO);
        }
        //5.构造返回结果
        return new PageListDTO<>(count,listDTO);
    }
}
